import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const WHITE_LIST = ['/login', '/404']
import { NOT_FOUND_ROUTE } from '@/router/constant'

/**
 * 路由守卫
 * @param {} router
 */
export function createPermissionGuard(router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const userStore = useUserStore()
    const permissionStore = usePermissionStore()
    const token = getToken()
    if (token) {
      if (to.path === '/login') {
        next({ path: '/login' })
        NProgress.done()
      } else {
        // 获取当前权限
        const hasRoles = userStore.getRoles && userStore.getRoles.length > 0
        if (hasRoles) {
          next()
          NProgress.done()
        } else {
          // 获取权限，根据权限获取对应的路由信息
          const { roles } = await userStore.getUserInfo('token')
          const accessRoutes = permissionStore.generateRoutes(roles)
          console.log('accessRoutes', accessRoutes)
          accessRoutes.forEach((route) => {
            !router.hasRoute(route.name) && router.addRoute(route)
          })
          router.addRoute(NOT_FOUND_ROUTE)
          next({ ...to, replace: true })
          NProgress.done()
        }
      }
    } else {
      if (WHITE_LIST.includes(to.path)) {
        next()
      } else {
        next(`/login?redirect=${to.path}`)
      }
      NProgress.done()
    }
  })
}
